#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
消息管理控制器
整合路由和控制器功能
"""

from flask import Blueprint, request
# 确保从正确的路径导入
import services.message_service
from utils.R import R
from settings import get_logger

# 使用完整的类引用
MessageService = services.message_service.MessageService

# API版本
API_VERSION = 'v1'

# 创建蓝图，设置URL前缀
message_bp = Blueprint('message', __name__, url_prefix=f'/api/{API_VERSION}/message')


class MessageController:
    """
    消息管理控制器
    整合路由和控制器功能
    """
    
    def __init__(self):
        self.message_service = MessageService()
        self.logger = get_logger(__name__)
        self._register_routes()
    
    def _register_routes(self):
        """
        注册所有路由
        """
        # 注册路由装饰器，路由前缀已在蓝图中设置，这里只需要指定具体路径
        message_bp.route('/send', methods=['POST'])(self.send_message)
        message_bp.route('/monitoring/start', methods=['POST'])(self.start_monitoring)
        message_bp.route('/monitoring/stop', methods=['POST'])(self.stop_monitoring)
        message_bp.route('/monitoring/status', methods=['GET'])(self.get_monitoring_status)
        message_bp.route('/auto-reply', methods=['POST'])(self.set_auto_reply_message)
    
    def send_message(self):
        """
        发送消息
        
        Returns:
            响应对象
        """
        try:
            # 从请求中获取数据
            data = request.get_json() or {}
            account_id=data.get('account_id')
            target = data.get('target')
            message = data.get('message')
            target_type = data.get('type', 'friend')
            
            # 参数校验
            if not account_id or not account_id.strip():
                self.logger.warning("账号参数:微信账号 不可为空")
                return R.fail(message="账号 微信账号 不能为空")

            if not target or not target.strip():
                self.logger.warning("目标参数:用户关系 不可为空")
                return R.fail(message="目标 用户关系 不能为空")
                
            if not message or not message.strip():
                self.logger.warning("发送的消息内容参数为空")
                return R.fail(message="消息内容不能为空")
            
            self.logger.info(f"发送消息，目标：{target}，类型：{target_type},消息内容：{message}")
            
            # 调用服务层方法
            result = self.message_service.send_message(account_id, target, message, target_type)
            print("result is" , result)
            if result.get('success'):
                return R.ok(data=result.get('message_id', {}), message=result.get('message', "消息发送成功"))
            else:
                return R.fail(message=result.get('error', "消息发送失败"))
                
        except Exception as e:
            self.logger.error(f"发送消息失败: {e}")
            return R.fail(message="发送消息失败")
    
    def start_monitoring(self):
        """
        启动消息监控
        
        Returns:
            响应对象
        """
        try:
            # 从请求中获取数据
            data = request.get_json() or {}
            print('data', data)
            # 从数据中获取账号
            account_id = data.get('account_id')
            # 开启监控的时间长度
            duration = data.get('duration', '1h')
            
            self.logger.info(f"启动消息监控，持续时间：{duration}")
            
            # 调用服务层方法
            result = self.message_service.start_monitoring(account_id,duration)
            
            if result.get('success'):
                return R.ok(data=result.get('data', {}), message=result.get('message', "消息监控已启动"))
            else:
                return R.fail(message=result.get('error', "启动消息监控失败"))
                
        except Exception as e:
            self.logger.error(f"启动消息监控失败: {e}")
            return R.fail(message="启动消息监控失败")
    
    def stop_monitoring(self):
        """
        停止消息监控
        
        Returns:
            响应对象
        """
        try:
            self.logger.info("停止消息监控")
            
            # 调用服务层方法
            result = self.message_service.stop_monitoring()
            
            if result.get('success'):
                return R.ok(data=result.get('data', {}), message=result.get('message', "消息监控已停止"))
            else:
                return R.fail(message=result.get('error', "停止消息监控失败"))
                
        except Exception as e:
            self.logger.error(f"停止消息监控失败: {e}")
            return R.fail(message="停止消息监控失败")
    
    def get_monitoring_status(self):
        """
        获取消息监控状态
        
        Returns:
            响应对象
        """
        try:
            self.logger.info("获取监控状态")
            
            # 调用服务层
            result = self.message_service.get_monitoring_status()
            
            if result.get('success'):
                return R.ok(data=result.get('data', {}))
            else:
                return R.fail(message=result.get('error', "获取监控状态失败"))
                
        except Exception as e:
            self.logger.error(f"获取监控状态失败: {e}")
            return R.fail(message="获取监控状态失败")
    
    def set_auto_reply_message(self):
        """
        设置自动回复消息
        
        Returns:
            响应对象
        """
        try:
            # 从请求中获取数据
            data = request.get_json() or {}
            message = data.get('message')
            
            # 参数校验
            if not message or not message.strip():
                self.logger.warning("回复消息参数为空")
                return R.fail(message="回复消息不能为空")
            
            self.logger.info(f"设置自动回复消息：{message}")
            
            # 调用服务层方法
            result = self.message_service.set_auto_reply_message(message)
            
            if result.get('success'):
                return R.ok(data=result.get('data', {}), message=result.get('message', "自动回复消息已设置"))
            else:
                return R.fail(message=result.get('error', "设置自动回复消息失败"))
                
        except Exception as e:
            self.logger.error(f"设置自动回复消息失败: {e}")
            return R.fail(message="设置自动回复消息失败")


# 实例化控制器，确保路由被注册
message_controller = MessageController()